<?php
/**
 *  @Copyright
 *
 *  @package     Display Searched Keywords - DSK for Joomla! 2.5
 *  @author      Viktor Vogel {@link http://www.kubik-rubik.de}
 *  @version     Version: 2.5-2 - 08-March-2012
 *  @link        Project Site {@link http://joomla-extensions.kubik-rubik.de/dsk-display-searched-keywords}
 *
 *  @license GNU/GPL
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
defined('_JEXEC') or die('Restricted access');

class mod_dskHelper extends JObject
{
    protected $_db;
    protected $_url;

    function __construct()
    {
        $this->set('_db', JFactory::getDbo());

        $uri = JFactory::getURI();
        $this->set('_url', $this->buildinternalurl($uri));
    }

    // Check whether the table for the module was already created
    function sql()
    {
        $query = "CREATE TABLE IF NOT EXISTS ".$this->_db->nameQuote('#__dsk')." (".$this->_db->nameQuote('url')." TINYTEXT NOT NULL, ".$this->_db->nameQuote('keywords')." TEXT NOT NULL)";
        $this->_db->setQuery($query);
        $this->_db->query();
    }

    // Save searchstrings
    function savekeyword($params)
    {
        $searchengine = $params->get('searchengine', 'http://www.google');

        if(preg_match('@http.?://@isU', $searchengine, $match))
        {
            $searchengine = str_replace($match, '', $searchengine);
        }

        $searchengine = 'http.?\://'.preg_quote($searchengine);
        $querystring = $params->get('querystring', 'q');

        if(isset($_SERVER['HTTP_REFERER']) AND $_SERVER['HTTP_REFERER'] !== null AND $_SERVER['HTTP_REFERER'] !== '')
        {
            $referrer = htmlspecialchars($_SERVER['HTTP_REFERER']);

            if(preg_match('@'.$searchengine.'@', $referrer))
            {
                preg_match('@'.$querystring.'=(.*)&@isU', $referrer, $searchstrings);

                if(!empty($searchstrings[1]))
                {
                    $keyword = urldecode($searchstrings[1]);
                }

                if($params->get('blacklistmode') == 1 OR $params->get('blacklistmode') == 3)
                {
                    // Blacklist - delete bad words
                    $badwords = explode(",", $params->get('blacklist'));

                    foreach($badwords as $badword)
                    {
                        $badword = preg_quote(trim($badword));

                        if($keyword = preg_replace('@'.$badword.'@iu', '', $keyword))
                        {
                            $keyword = preg_replace('@\s+@', ' ', $keyword);
                        }
                    }
                }

                if(!empty($keyword))
                {
                    $limit = $params->get('limit', 5);

                    // Check whether the url is already in the database
                    $query = "SELECT * FROM ".$this->_db->nameQuote('#__dsk')." WHERE ".$this->_db->nameQuote('url')." = ".$this->_db->quote($this->_url);
                    $this->_db->setQuery($query);
                    $this->_db->query();
                    $row = $this->_db->loadRow();

                    if(!empty($row))
                    {
                        $separator = $params->get('separator');

                        $keywordarray = explode($separator, $row[1]);

                        // Do not save same searchstring
                        foreach($keywordarray as $element)
                        {
                            if($keyword == $element)
                            {
                                return;
                            }
                        }

                        // Add new keyword at first place
                        array_unshift($keywordarray, $keyword);

                        // Remove elements from array if limit is achieved
                        if(count($keywordarray) >= $limit)
                        {
                            array_splice($keywordarray, $limit);
                        }

                        // Convert array to string and save in the database
                        $keywords = implode($separator, $keywordarray);

                        $query = "UPDATE ".$this->_db->nameQuote('#__dsk')." SET ".$this->_db->nameQuote('keywords')." = ".$this->_db->quote($keywords)." WHERE ".$this->_db->nameQuote('url')." = ".$this->_db->quote($this->_url);
                        $this->_db->setQuery($query);
                        $this->_db->query();
                    }
                    else
                    {
                        // New entry in the database
                        $query = "INSERT INTO ".$this->_db->nameQuote('#__dsk')." (".$this->_db->nameQuote('url').", ".$this->_db->nameQuote('keywords').") VALUES (".$this->_db->quote($this->_url).", ".$this->_db->quote($keyword).")";
                        $this->_db->setQuery($query);
                        $this->_db->query();
                    }
                }
            }
        }
    }

    // Load searchstrings
    function loadkeywords($params)
    {
        // Load parameter
        $separator = $params->get('separator');

        // Read keywords from database
        $query = "SELECT ".$this->_db->nameQuote('keywords')." FROM ".$this->_db->nameQuote('#__dsk')." WHERE ".$this->_db->nameQuote('url')." = ".$this->_db->quote($this->_url);
        $this->_db->setQuery($query);
        $result = $this->_db->loadResult();

        $keywords = explode($separator, $result);

        // Blacklist - delete bad words
        if($params->get('blacklistmode') == 2 OR $params->get('blacklistmode') == 3)
        {
            $badwords = explode(",", $params->get('blacklist'));
            $keywordsclean = array();

            foreach($keywords as $keyword)
            {
                foreach($badwords as $badword)
                {
                    $badword = preg_quote(trim($badword));

                    if($keyword = preg_replace('@'.$badword.'@iu', '', $keyword))
                    {
                        $keyword = preg_replace('@\s+@', ' ', $keyword);
                    }
                }

                if($keyword != '')
                {
                    $keywordsclean[] = trim($keyword);
                }
            }

            unset($keywords);
            $keywords = array_unique($keywordsclean);
        }

        $limit = count($keywords);

        $output = '';

        if(!empty($keywords[0]))
        {
            $list = $params->get('list', 0);
            $text = $params->get('text', '');
            $delimiter = $params->get('delimiter', '');
            $style = $params->get('style');

            if($style == 1)
            {
                $style_start = '<strong>';
                $style_end = '</strong>';
            }
            elseif($style == 2)
            {
                $style_start = '<em>';
                $style_end = '</em>';
            }
            else
            {
                $style_start = '';
                $style_end = '';
            }


            if(!empty($text))
            {
                $output .= $style_start.$text.$style_end;
            }

            // Write output
            if($list == 1)
            {
                $output .= '<ul>'.$style_start;

                foreach($keywords as $keyword)
                {
                    $output .= '<li>'.$keyword.'</li>';
                }

                $output .= $style_end.'</ul>';
            }
            elseif($list == 0)
            {
                $count = 1;
                $output .= $style_start;

                foreach($keywords as $keyword)
                {
                    $output .= ' '.$keyword.' ';

                    if($count < $limit)
                    {
                        $output .= $delimiter;
                    }

                    $count++;
                }

                $output .= $style_end;
            }
        }

        return $output;
    }

    // Delete saved keywords
    function deletekeywords($params)
    {
        if($params->get('delete') == 1)
        {
            $query = "TRUNCATE TABLE ".$this->_db->nameQuote('#__dsk');
            $this->_db->setQuery($query);
            $this->_db->query();
        }
        elseif($params->get('delete') == 2)
        {
            $query = "DELETE FROM ".$this->_db->nameQuote('#__dsk')." WHERE ".$this->_db->nameQuote('url')." = ".$this->_db->quote($this->_url);
            $this->_db->setQuery($query);
            $this->_db->query();
        }

        return;
    }

    // Build internal URL - indepedent of SEF function
    function buildinternalurl($uri)
    {
        // Reference to JRouter object
        $route = JSite::getRouter();

        // Get the path to avoid an error because of the method -parse- in the next step
        $properties = array('_vars' => '', '_uri' => '', '_scheme' => '', '_query' => '', '_path' => '', '_host' => '', '_errors' => '');

        foreach($properties as $key => $value)
        {
            $properties[$key] = $uri->get($key);
        }

        // Get the internal route
        $url_internal_array = $route->parse($uri);

        // Set the right properties back to the JURI object
        foreach($properties as $key => $value)
        {
            $uri->set($key, $value);
        }

        // Move Itemid at the end
        if(array_key_exists('Itemid', $url_internal_array))
        {
            $itemid = $url_internal_array['Itemid'];
            unset($url_internal_array['Itemid']);
            $url_internal_array['Itemid'] = $itemid;
        }

        // Move lang at the end
        if(array_key_exists('lang', $url_internal_array))
        {
            $lang = $url_internal_array['lang'];
            unset($url_internal_array['lang']);
            $url_internal_array['lang'] = $lang;
        }

        $url_internal = JURI::base().'index.php?'.JURI::buildQuery($url_internal_array);

        return $url_internal;
    }

}
?>